import 'package:flutter/material.dart';

class ComFadeIn extends StatefulWidget {
  final Widget child;
  final Offset offset; // 左往右
  final Duration delay; // 延迟执行

  const ComFadeIn({
    super.key,
    required this.child,
    this.offset = const Offset(-10, 0),
    this.delay = const Duration(seconds: 0),
  });

  @override
  State<ComFadeIn> createState() => _ComFadeInState();
}

class _ComFadeInState extends State<ComFadeIn>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  late AnimationController _controller;
  late Tween<double> opacityTween; // 透明度
  late Tween<Offset> offsetTween; // 位移
  late Animation<double> opacityAnimation;
  late Animation<Offset> offsetAnimation;
  late CurveTween curveTween;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 1),
    );
    curveTween = CurveTween(curve: Curves.easeInOut);
    opacityTween = Tween(begin: 0, end: 1);
    offsetTween = Tween(begin: widget.offset, end: Offset.zero);
    opacityAnimation = opacityTween.animate(_controller.drive(curveTween));
    offsetAnimation = offsetTween.animate(_controller.drive(curveTween));
    Future.delayed(widget.delay, () {
      _controller.forward();
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return AnimatedBuilder(
      animation: opacityAnimation,
      builder: (ctx, child) {
        return Opacity(
          opacity: opacityAnimation.value,
          child: AnimatedBuilder(
            animation: offsetAnimation,
            builder: (ctx, child) {
              return Transform.translate(
                offset: offsetAnimation.value,
                child: child,
              );
            },
            child: child,
          ),
        );
      },
      child: widget.child,
    );
  }

  @override
  bool get wantKeepAlive => true;
}
